<template>
  <view class="page">
    <view class="section">
      <view class="main-card">
        <view class="">
          <view class="items-start">
            <text class="font text">扫描附近设备</text>
            <!--  <text class="mt-10 text_2">持续自动搜索中...</text> -->
            <view class="spinner">
              <text class="mt-10 text_2">自动搜寻附近设备中</text>
              <view class="bounce1"></view>
              <view class="bounce2"></view>
              <view class="bounce3"></view>
            </view>
          </view>
          <view class="centerd">
            <image class="image" src="../../static/images/e36b9ff03e325d6412ce5f55afb31ad8.png"/>
            <text class="text_3 mt-7">请将手机尽量靠近要添加的设备</text>
          </view>
        </view>
        <view class="mt-51">
          <view v-if="buleTooth=='STATE_OFF'" class="buleToothTip" @click="turnOnBlueTooth()">
            <text class="text_4">请开启蓝牙以发现设备</text>
          </view>
          <view v-if="findDevice">
            <scroll-view scroll-y="true" class="scroll-Y">
              <button v-for="(value, key, index) in devices" class="scroll-view-item"
                      @click="onConn(key)">{{ value }}
              </button>
            </scroll-view>
          </view>
          <view v-else>
            <text class="self-stretch text_5 mt-11">
              未找到设备,请查看蓝牙/gps状态，是否获取到相关权限，或者离设备近一点。
            </text>
          </view>
        </view>
      </view>
      <view class="mini-card" @click="navTo('/pages/scan/scan')">
        <view class="centerd">
          <image class="image_2" src="../../static/images/8b75be695e6665ef59daa2f7f5765f45.png"/>
          <text class="font_2 text_6">扫码添加</text>
        </view>
        <view class="centerd">
          <image class="image_2" src="../../static/images/81608a0171c2398140a333b19fdc76bc.png"/>
          <text class="font_2 text_6">其他平台</text>
        </view>
      </view>

      <!-- 新增设备选择区域 -->
      <view class="device-select-card">
        <view class="search-bar">
          <text class="search-label">选择设备型号</text>
          <view class="search-input-container">
            <input type="text" class="search-input" placeholder="搜索设备型号" v-model="searchModel" />
            <image class="search-icon" src="../../static/images/e36b9ff03e325d6412ce5f55afb31ad8.png" />
          </view>
        </view>

        <view class="category-tabs">
          <view
              v-for="(tab, index) in tabs"
              :key="index"
              class="category-tab"
              :class="{ active: activeTab === index }"
              @click="activeTab = index"
          >
            <text>{{ tab }}</text>
          </view>
        </view>

        <scroll-view class="device-grid" scroll-y="true">
          <view class="device-list">
            <view
                v-for="(device, index) in filteredDevices"
                :key="index"
                class="device-item"
                @click="selectDevice(device)"
            >
              <image class="device-image" :src="device.image" />
              <text class="device-name">{{ device.name }}</text>
              <text class="device-brand">{{ device.brand || '共享设备' }} | {{ device.status || '设备高达' }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <view>
      <uni-popup ref="popup" :is-mask-click="true" mask-background-color="rgba(0,0,0,0)">
        <bluewifi
            :SSID="SSID"
            :password="password"
            :result="result"
            :serialnum_equip="serialnum_equip"
            @wifi-info-updated="onWifiInfoUpdated"
        ></bluewifi>
      </uni-popup>
    </view>
    <view>
      <uni-popup ref="gps" :is-mask-click="true" mask-background-color="rgba(0,0,0,0)">
        <view class="remind">
          <view class="wrap">
            <text class="text_9">搜索蓝牙设备需要打开定位权限。</text>
            <view>
              <button class="button" @click="cancle()">取消</button>
              <button class="button" @click="turnOnGps()">开启定位</button>
            </view>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script>
import bluewifi from "@/components/bluewifi/bluewifi.vue";
import { _bindequips, _updateNetworkInfo } from '@/service/equip.js'
import { _applysharing } from '@/service/sharingequip.js'

const EspTouch = uni.requireNativePlugin('SZW-EspTouch');
export default {
  components: {
    bluewifi
  },
  data() {
    return {
      timer: null,
      timeNum: 0,
      animationData: {},
      animation: {},
      gps: 'close',
      buleTooth: 'STATE_OFF',
      init: '',
      gpsSwitchStateReceiver: null,
      findDevice: false,
      searchID: null,
      stopSearchID: null,
      devices: {},
      result: false,
      SSID: "",
      password: "",
      serialnum_equip: "",
      currentDeviceAddress: "",
      // scale:1,
      // 新增数据
      searchModel: "",
      activeTab: 0,
      flag:false,
      str:"",
      tabs: ["加热炉", "粉碎器", "搅拌机"],
      deviceCategories: {
        "加热炉": [
          { name: "KJ 1600°C箱式电阻炉", image: "../../static/images/51276e00a4890f11936fcc00b81e6367.png", brand: "运通牌", status: "设备高达" },
          { name: "加热炉1", image: "../../static/images/51276e00a4890f11936fcc00b81e6367.png", brand: "共享设备", status: "设备高达" },
          { name: "加热炉2", image: "../../static/images/51276e00a4890f11936fcc00b81e6367.png", brand: "原粹牌", status: "设备高达" },
          { name: "加热炉3", image: "../../static/images/51276e00a4890f11936fcc00b81e6367.png", brand: "共享设备", status: "设备高达" }
        ],
        "粉碎器": [
          { name: "粉碎器1", image: "../../static/images/51276e00a4890f11936fcc00b81e6367.png" },
          { name: "粉碎器2", image: "../../static/images/51276e00a4890f11936fcc00b81e6367.png" }
        ],
        "搅拌机": [
          { name: "搅拌机1", image: "../../static/images/51276e00a4890f11936fcc00b81e6367.png" },
          { name: "搅拌机2", image: "../../static/images/51276e00a4890f11936fcc00b81e6367.png" }
        ]
      },
      deviceCache: {},  // 设备缓存
      lastSearchTime: 0,  // 上次搜索时间
      isSearching: false
    };
  },
  computed: {
    filteredDevices() {
      const categoryDevices = this.deviceCategories[this.tabs[this.activeTab]] || [];

      if (!this.searchModel) {
        return categoryDevices;
      }

      return categoryDevices.filter(device =>
          device.name.toLowerCase().includes(this.searchModel.toLowerCase())
      );
    }
  },
  onLoad() {
    // 初始化蓝牙
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      console.log('页面加载时获取到用户信息:', userInfo);
      this.currentUser = userInfo.accountNum;
    }

    this.$blueToothTool.init({
      listenBTStatusCallback: this.initBlueTootn,
      discoveryDeviceCallback: this.onDevice,
      discoveryFinishedCallback: () => {
        console.log("搜索完成");
      },
      readDataCallback: (dataByteArr) => {
        if (dataByteArr[0] === 79) {
          this.$api.msg('网络连接成功');
          console.log('网络连接成功');

          // 停止蓝牙搜索
          this.stopFindBule();

          // 关闭弹窗
          this.$refs.popup.close();

          // 处理配网成功后的逻辑
          this.handleNetworkSuccess();
        }
        else if (dataByteArr[0] === 78) {
          this.$api.msg('WIFI名或WIFI密码错误');
          console.log('WIFI名或WIFI密码错误');
          this.$refs.popup.close();
        }
        else {
          for(let i=0;i<dataByteArr.length;i++){
            if(dataByteArr[i]===40){
              this.str="";
              this.flag=true;
            }else if (dataByteArr[i]===41){
              this.flag=false;
              this.serialnum_equip=this.str;
              console.log('设备号：'+ this.str)
              // 开始配网加载提示
              uni.showLoading({
                title: '正在配网中',
                mask: true
              });
            }
            else{
              if(this.flag){
                this.str+=(dataByteArr[i]-48);
              }
            }
          }
        }
      },
      connExceptionCallback: (e) => {
        console.error("设备连接失败:", e);
        uni.showToast({
          title: '设备连接失败',
          icon: 'none'
        });
      }
    });
  },
  onReady() {
    console.log("页面加载完成");
  },
  mounted() {
    // this.$refs.gps.open('bottom');
    try {
      const main = plus.android.runtimeMainActivity();
      const Settings = plus.android.importClass("android.provider.Settings");
      const BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
      const IntentFilter = plus.android.importClass('android.content.IntentFilter');
      const LocationManager = plus.android.importClass("android.location.LocationManager");
      const Secure = Settings.Secure;
      const locationMode = Secure.getInt(main.getContentResolver(), Secure.LOCATION_MODE);
      const adapter = BluetoothAdapter.getDefaultAdapter();

      if (!adapter) {
        console.error("设备不支持蓝牙");
        return;
      }

      if (!locationMode) {
        this.$blueToothTool.shortToast("请授予定位权限");
        this.$refs.gps.open('bottom');
      } else {
        this.gps = 'open';
      }

      if (!adapter.isEnabled()) {
        this.$blueToothTool.shortToast("请开启蓝牙权限");
        adapter.enable();
      } else {
        this.buleTooth = 'STATE_ON';
      }

      if (this.buleTooth === 'STATE_ON' && this.gps === 'open') {
        setTimeout(() => {
          this.initBlueTootn(this.buleTooth);
        }, 250);
        this.searchID = setInterval(() => {
          this.initBlueTootn(this.buleTooth)
        }, 15000);//每隔15秒检测一次状态
      }

      this.gpsSwitchStateReceiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
        "onReceive": (context, intent) => {
          try {
            plus.android.importClass(context);
            plus.android.importClass(intent);
            if (intent.getAction() === LocationManager.PROVIDERS_CHANGED_ACTION) {
              const locationManager = context.getSystemService(context.LOCATION_SERVICE);
              const gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

              this.gps = gpsEnabled ? 'open' : 'close';
              gpsEnabled ? this.initBlueTootn(this.buleTooth) : this.stopFindBule();
              console.log(gpsEnabled ? "GPS 已启用" : "GPS 已关闭");
            }
          } catch (e) {
            console.error("定位状态接收器处理失败:", e);
          }
        }
      });

      main.registerReceiver(this.gpsSwitchStateReceiver, new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION));

    } catch (e) {
      console.error("初始化失败:", e);
    }
  },
  onShow() {
    if (Object.keys(this.devices).length === 0) {
      this.findDevice = false;
    }
  },
  beforeDestroy() {
    let main = plus.android.runtimeMainActivity();
    main.unregisterReceiver(this.gpsSwitchStateReceiver);
    this.stopSearchID && clearTimeout(this.stopSearchID);
    this.searchID && clearInterval(this.searchID);
    this.stopFindBule();
    this.$blueToothTool.unInit();
  },
  methods: {
    selectDevice(device) {
      uni.showToast({
        title: `已选择 ${device.name}`,
        icon: 'success',
        duration: 2000
      });
      console.log('选择设备:', device);
      // 可以在这里添加设备处理逻辑
    },

    // 处理配网成功后的逻辑
    async handleNetworkSuccess() {
      try {
        console.log('开始处理配网成功后的逻辑');
        
        // 更新设备网络信息
        await this.updateDeviceNetworkInfo();

        // 绑定设备
        const bindResult = await this.bindDevice();
        if (!bindResult) {
          console.log('设备绑定失败或已取消');
          return;
        }

      } catch (error) {
        console.error('处理配网成功后的操作失败:', error);
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 更新设备网络信息
    async updateDeviceNetworkInfo() {
      try {
        console.log('开始更新设备网络信息');
        const networkInfo = {
          ssid: this.SSID,
          bssid: this.BSSID,
          ipAddress: '192.168.1.100', // 这里应该是实际的IP地址，但在配网过程中可能无法获取
          macAddress: this.BSSID
        };
        
        const res = await _updateNetWorkInfo({
          serialnum_equip: this.serialnum_equip,
          networkInfo: networkInfo
        });
        
        console.log('设备网络信息更新结果:', res);
        if (res.flag) {
          console.log('设备网络信息更新成功');
        } else {
          console.warn('设备网络信息更新失败:', res.message);
        }
      } catch (error) {
        console.error('更新设备网络信息时出错:', error);
      }
    },
    
    // 监听WiFi信息更新事件
    onWifiInfoUpdated(wifiInfo) {
      console.log('收到WiFi信息更新:', wifiInfo);
      this.SSID = wifiInfo.ssid;
      this.password = wifiInfo.password;
    },

    // 执行绑定设备
    async bindDevice() {
      try {
        console.log('开始绑定设备，serialnum_equip:', this.serialnum_equip, 'currentUser:', this.currentUser);

        if (!this.serialnum_equip) {
          console.error('设备号未定义');
          uni.showToast({
            title: '设备号未定义，请先获取设备信息',
            icon: 'none'
          });
          return false;
        }

        if (!this.currentUser) {
          console.error('用户信息未定义');
          uni.showToast({
            title: '用户信息未定义，请先登录',
            icon: 'none'
          });
          return false;
        }

        const res = await _bindequips({
          serialnum_equip: this.serialnum_equip,
          account_user: this.currentUser
        });
        console.log('设备绑定接口返回:' + res);

        //申请共享操作
        if (res.message.includes('该设备已被')) {
          return new Promise((resolve, reject) => {
            uni.showModal({
              title: '提示',
              content: `本设备已被绑定，请申请共享`,
              confirmText: '申请共享',
              success: async (res) => {
                if (res.confirm) {
                  console.log('用户申请共享设备');
                  uni.hideLoading(); // 隐藏加载提示
                  
                  // 显示申请结果模态框
                  uni.showModal({
                    title: '申请结果',
                    content: '申请成功，请耐心等待绑定人同意\n系统将在后台自动处理您的申请',
                    showCancel: false,
                    success: (result) => {
                      if (result.confirm) {
                        resolve(true);
                      }
                    }
                  });
                  
                  await this.applySharing();
                } else {
                  uni.hideLoading(); // 隐藏加载提示
                  resolve(false);
                }
              }
            });
          });
          // 返回绑定结果
          return true;
        }
        //已经绑定操作
        else if (res.message.includes('您已绑定该设备')) {
          console.log('设备已绑定当前用户');
          uni.showModal({
            title: '提示',
            content: '您已绑定该设备，是否更新为待机状态？',
            success: (res_modal) => {
              if (res_modal.confirm) {
                console.log('用户确认更新设备状态');
                uni.hideLoading(); // 隐藏加载提示
                uni.reLaunch({
                  url: '/pages/index1/index1',
                  success: () => {
                    console.log('成功重新启动并跳转到首页');
                  },
                  fail: (err) => {
                    console.error('页面跳转失败，请检查页面路径或配置', err);
                  }
                });
              }
            }
          });
          return true;
        }
        //设备绑定成功操作
        else if (res.message.includes('设备绑定成功')) {
          console.log('设备绑定成功');
          uni.showModal({
            title: '提示',
            content: '该设备尚未绑定，是否立即绑定？',
            success: (res_modal) => {
              if (res_modal.confirm) {
                console.log('用户确认绑定设备');
                uni.hideLoading(); // 隐藏加载提示
                uni.reLaunch({
                  url: `/pages/device-setup/device-setup?serialnum_equip=${this.serialnum_equip}`,
                  success: () => {
                    console.log('成功重新启动并跳转到设备设置页面');
                  },
                  fail: (err) => {
                    console.error('页面跳转失败，请检查页面路径或配置', err);
                  }
                });
              }
            }
          });
        }
      } catch (error) {
        console.error('绑定设备失败:', error);
        uni.showToast({
          title: '绑定设备失败',
          icon: 'none',
          duration: 2000
        });
        return false;
      }
    },

    // 申请共享
    async applySharing() {
      try {
        console.log('开始申请设备共享');
        const data = {
          serialnum_sharingequip: this.serialnum_equip,
          account_sharingequip: this.currentUser
        };
        //向后端发送申请共享请求
        const res = await _applysharing(data);
        console.log('设备申请接口返回:', res);

        if (res.message.includes('申请成功')){
          console.log('申请成功，请耐心等待绑定人同意');
          
          // 显示申请结果模态框
          uni.showModal({
            title: '申请结果',
            content: '申请成功，请耐心等待绑定人同意\n系统将在后台自动处理您的申请\n您可以在通知中心查看申请进度',
            showCancel: false,
            success: (result) => {
              if (result.confirm) {
                // 用户点击确定后继续执行
                uni.showToast({
                  title: '已知晓',
                  icon: 'none'
                });
              }
            }
          });
          
          uni.showToast({
            title: '申请成功',
            icon: 'success'
          });
        }
      } catch (error) {
        console.error('申请共享失败:', error);
        uni.showToast({
          title: '申请共享失败',
          icon: 'none'
        });
      }
    },

    //原有方法
    cancle(){
      this.$refs.gps.close();
      // 隐藏加载提示
      uni.hideLoading();
    },
    turnOnGps() {
      try {
        const main = plus.android.runtimeMainActivity(); // 获取当前运行的主Activity实例
        const Intent = plus.android.importClass('android.content.Intent'); // 导入android.content.Intent类
        const Settings = plus.android.importClass("android.provider.Settings"); // 导入android.provider.Settings类
        const intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); // 创建Intent并设置动作
        main.startActivity(intent); // 启动Intent，打开位置设置页面
        this.$refs.gps.close(); // 关闭GPS弹窗
        // 隐藏加载提示
        uni.hideLoading();
      } catch (error) {
        console.error("无法打开定位设置:", error); // 记录错误信息
      }
    },
    turnOnBlueTooth() {
      try {
        const BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter"); // 导入android.bluetooth.BluetoothAdapter类
        const adapter = BluetoothAdapter.getDefaultAdapter(); // 获取默认的蓝牙适配器

        if (!adapter) {
          console.error("设备不支持蓝牙");
          return;
        }

        if (!adapter.isEnabled()) {
          adapter.enable();
          // 隐藏加载提示
          uni.hideLoading();
        }
        else {
          this.buleTooth = 'STATE_ON';
        }

        // if (this.buleTooth === 'STATE_ON' && this.gps === 'open') {
        //   setTimeout(() => {
        //     this.initBlueTootn(this.buleTooth)
        //   }, 250);
        //   this.searchID = setInterval(() => {
        //     this.initBlueTootn(this.buleTooth)
        //   }, 15000);//每隔15秒检测一次状态
        // }

      } catch (error) {
        console.error("启用蓝牙失败:", error);
      }
    },

    initBlueTootn(state) {
      this.buleTooth = state;

      if (state !== 'STATE_ON' || this.gps !== 'open') {
        this.stopFindBule();
        console.log(state, this.gps);
        // this.$api.msg('未发现蓝牙设备，请检查是否开启定位权限或者离设备近一些。');
        return; // 提前返回，避免不必要的执行
      }

      // const lastBleAddress = uni.getStorageSync('lastBleAddress');
      // if (lastBleAddress) {
      //   setTimeout(()=>{},250);
      //   uni.showLoading({
      //     title: '正在连接历史设备...'
      //   });
      //
      //   this.$blueToothTool.connDevice(lastBleAddress, (result) => {
      //     uni.hideLoading();
      //     console.log("连接", result);
      //     this.result = result;
      //     this.handleConnectionResult(result, lastBleAddress);
      //   });
      // } else {
      this.searchBle();
      // }
    },

    // handleConnectionResult(result, address) {
    //   if (result) {
    //     this.result = result;
    //     // uni.setStorageSync('lastBleAddress', item.address);
    //     uni.hideLoading();
    //
    //     console.log('连接结果：', this.result);
    //     if (result) {
    //       console.log('蓝牙连接成功，打开弹窗');
    //       this.$refs.popup.open('center');
    //       this.getWifiInfo();
    //       this.stopFindBule();
    //
    //       // 当成功连接设备时，更新设备缓存
    //       if (!this.devices[address]) {
    //         this.devices[address] = `ESP Device ${Object.keys(this.devices).length + 1}`;
    //         this.deviceCache = { ...this.devices };
    //         // 开始配网加载提示
    //         uni.showLoading({
    //           title: '正在配网中',
    //           mask: true
    //         });
    //       }
    //     }
    //     uni.showToast({
    //       title: result ? '连接成功！' : '连接失败...'
    //     });
    //
    //     if (!result) {
    //       this.searchBle();
    //       // 隐藏加载提示
    //       uni.hideLoading();
    //     }
    //   }
    // },

    searchBle() {
      console.log("initBule");

      // 如果正在搜索，直接返回
      if (this.isSearching) {
        console.log('蓝牙搜索正在进行中，跳过本次搜索');
        return;
      }

      this.isSearching = true;
      // 使用Promise来处理异步操作
      const openBluetoothAdapterPromise = () => {
        return new Promise((resolve, reject) => {
          uni.openBluetoothAdapter({
            success: resolve,
            fail: reject
          });
        });
      };

      const getBluetoothAdapterStatePromise = () => {
        return new Promise((resolve, reject) => {
          uni.getBluetoothAdapterState({
            success: resolve,
            fail: reject
          });
        });
      };

      openBluetoothAdapterPromise()
          .then(res => {
            console.log('蓝牙适配器打开成功');
            return getBluetoothAdapterStatePromise();
          })
          .then(res => {
            if (res.available) {
              console.log("开始搜寻附近的蓝牙外围设备");
              this.devices = {}; // 清空数组
              this.$blueToothTool.discoveryNewDevice();
              this.stopSearchID = setTimeout(() => {
                this.stopFindBule();
                console.log("10秒了，停止搜索");
                console.log(this.devices)

                // 更新缓存和状态
                this.isSearching = false;
                this.lastSearchTime = new Date().getTime();
                this.deviceCache = { ...this.devices };
              }, 10000);
            } else {
              console.log('本机蓝牙不可用');
              this.isSearching = false;
              return Promise.reject('本机蓝牙不可用');
            }
          })
          .catch(err => {
            console.error('操作失败:', err);
            this.isSearching = false;
            this.$api.msg('也许蓝牙和定位没开，或者没权限？');
          });
    },

    // startWith(str1, str2) {
    //   // return true;
    //   console.log(str2)
    //   if (str2 == null || str2 == "" || str1.length == 0 || str2.length > str1.length) {
    //     return false;
    //   }
    //   if (str1.substr(0, str2.length) == str2) {
    //     return true;
    //   } else {
    //     return false;
    //   }
    //   return true;
    // },


    onDevice(newDevice) {
      console.log("发现设备-" + newDevice.name + "，地址-" + newDevice.address)
      try {
        if (newDevice.name && newDevice.name !== 'null' && String(newDevice.name).startsWith("ESP")) {
          console.log('匹配到 ESP 设备:', newDevice);
          this.findDevice = true;
          this.devices[newDevice.address] = newDevice.name;
          this.devices = {
            ...this.devices
          }
        }
      } catch (e) {
        console.error(e)
      }

    },
    stopFindBule() {
      console.log("停止搜寻附近的蓝牙外围设备---------------")
      this.$blueToothTool.cancelDiscovery();
    },
    onConn(address) {
      console.log("连接蓝牙---------------" + address)
      uni.showLoading({
        title: '连接中',
        mask: false
      });

      this.$blueToothTool.connDevice(address, (result) => {
        if (result) {
          this.result = result;
          // uni.setStorageSync('lastBleAddress', item.address);
          uni.hideLoading();
        }
        console.log('连接结果：', this.result);
        if (result) {
          console.log('蓝牙连接成功，打开弹窗');
          this.$refs.popup.open('center');
          this.getWifiInfo();

          // 当成功连接设备时，更新设备缓存
          if (!this.devices[address]) {
            this.devices[address] = `ESP Device ${Object.keys(this.devices).length + 1}`;
            this.deviceCache = { ...this.devices };
          }
        }
        uni.showToast({
          title: result ? '连接成功！' : '连接失败...'
        });

        if (!result) {
          this.searchBle();
          // 隐藏加载提示
          uni.hideLoading();
        }
      });
    },
    getWifiInfo() {
      console.log('获取WiFi信息');
      EspTouch.getWifiInfo({}, result => {
        try {
          console.log(result);
          this.SSID = result.SSID;
          this.BSSID = result.BSSID;

          if (result.SSID === 'unknown ssid') {
            console.log('未联网，未开权限');
            this.loadWifiInfo();
          }
        } catch (error) {
          console.error('获取WiFi信息失败:', error);
          // 隐藏加载提示
          uni.hideLoading();
        }
      });
    },

    loadWifiInfo() {
      console.log('提示用户连接WiFi');
      uni.showModal({
        title: '请连接WIFI',
        content: '连接WIFI后才能获取到信息，如果你有其他选择，也可以点击取消按钮，选择手动输入。',
        showCancel: true,
        success: function (res) {
          console.log(res)
          if (res.confirm) {
            // 打开wifi设置页
            const main = plus.android.runtimeMainActivity();
            const Intent = plus.android.importClass("android.content.Intent");
            const mIntent = new Intent('android.settings.WIFI_SETTINGS');
            main.startActivity(mIntent);
            // 隐藏加载提示
            uni.hideLoading();
          }
        }
      });
    },

    // 取消智能配网
    cancelEsp() {
      EspTouch.cancel();
    },
    navTo(url) {
      uni.navigateTo({
        url: url,
      })
    }

    //  // 开始智能配网
    //  smartConfig() {
    // let info = EspTouch.smartConfig(
    //   {
    // 	bssid: '4C:C6:4C:0B:5D:0A', // 设备的MAC地址
    // 	ssid: '12345678', // WiFi的SSID
    // 	password: '12345678', // WiFi的密码
    // 	deviceCount: '10', // 设备数量
    // 	broadcast: 'true', // 是否广播
    //   },
    //   result => {
    // 	const msg = JSON.stringify(result);

    // 	if (result.type == 'begin') {
    // 	  uni.showToast({ title: '配置开始', duration: 1500 });
    // 	} else if (result.type == 'stepOk') {
    // 	  uni.showToast({ title: '发现并配置了一个设备:' + msg, duration: 1500 });
    // 	} else if (result.type == 'stepFailed') {
    // 	  uni.showToast({ title: '配置失败：' + msg, duration: 1500 });
    // 	} else if (result.type == 'end') {
    // 	  uni.showToast({ title: '配置结束', duration: 1500 });
    // 	}
    //   }
    // );
    //  },
    //  // 取消智能配网
    //  cancel() {
    // EspTouch.cancel();
    //  },
    //  getConnectedDevices() {
    //     // 调用Esptouch插件的API获取已连接设备的列表
    //     EspTouch.getConnectedDevices().then(devices => {
    //       this.connectedDevices = devices;
    //     }).catch(error => {
    //       console.error('Error getting connected devices:', error);
    //     });
    //   },
  },
};
</script>

<style scoped lang="scss">
.remind {
  background-color: #ffffff;
  width: 100vw; /* 宽度与屏幕一样 */
  height: 25vh; /* 高度占屏幕30% */
  border-radius: 20px 20px 0 0; /* 左上和右上角圆角 */
  box-shadow: 0px -2rpx 10rpx 4rpx rgba(0, 0, 0, 0.25);

  .wrap {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 30rpx;
  }

  .button {
    color: #000000;
    margin-top: 20rpx;
    background-color: #f3f3f3;
    border-color: #ffffff;
    border-style: solid;
    border-width: 1px;
    font-size: 14px;
    &:active {
      background-color: #e8e8e8;
    }
  }
}

.mt-7 {
  margin-top: 15rpx;
}

.mt-51 {
  margin-top: 105rpx;
}

.mt-11 {
  margin-top: 20rpx;
}

.mt-9 {
  margin-top: 20rpx;
}

.page {
  //#ifdef APP-PLUS
  height: 100vh;
  //#endif
  //#ifdef H5
  height: calc(100vh - 44px);
  //#endif
  padding-bottom: 5rpx;
  background-color: #ffffff;
}

.section {
  height: 140%;
  padding: 30rpx 30rpx;
  background-color: #e5e5e569;
}

.main-card {
  padding: 30rpx;
  background-color: #ffffff;
  border-radius: 50rpx;
}

.font {
  font-size: 40rpx;
  line-height: 20rpx;
}

.text {
  color: #000000;
  font-weight: 800;
}

.text_2 {
  color: #000000;
  font-size: 30rpx;
  line-height: 20rpx;
  margin-top: 30rpx;
}

.centerd {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image {
  width: 185rpx;
  height: 235rpx;
  margin-top: 50rpx;
  display: flex;
}

.text_3 {
  color: #808080;
  font-size: 30rpx;
  line-height: 20rpx;
}

.group {
  margin-left: 20rpx;
}

.text_4 {
  color: #d43030;
  font-size: 30rpx;
  line-height: 25rpx;
}

.text_5 {
  color: #d43030;
  font-size: 25rpx;
  line-height: 35rpx;
}

.mini-card {
  display: flex;
  align-items: center;
  justify-content: space-around;
  background-color: #ffffff;
  border-radius: 50rpx;
  padding: 30rpx;
  margin-top:15rpx;
}

.image_2 {
  width: 60rpx;
  height: 60rpx;
}

.font_2 {
  font-size: 25rpx;
  line-height: 20rpx;
  color: #000000;
  margin-top: 20rpx;
}

.text_6 {
  line-height: 15rpx;
}

element.style {
  display: flex;
  dispiay: flex;
  /* align-items: center; */
  justify-content: space-between;
}

.spinner {
  margin-top: 30rpx;
}

.spinner > view {
  width: 6px;
  height: 6px;
  background-color: #AAAAAA;

  border-radius: 100%;
  display: inline-block;
  -webkit-animation: bouncedelay 1.6s infinite ease-in-out;
  animation: bouncedelay 1.6s infinite ease-in-out;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

.spinner .bounce1 {
  -webkit-animation-delay: -0.32s;
  animation-delay: -0.32s;
}

.spinner .bounce2 {
  -webkit-animation-delay: -0.16s;
  animation-delay: -0.16s;
}

@-webkit-keyframes bouncedelay {

  0%,
  80%,
  100% {
    -webkit-transform: scale(0.0)
  }

  40% {
    -webkit-transform: scale(0.5)
  }
}

@keyframes bouncedelay {

  0%,
  80%,
  100% {
    transform: scale(0.0);
    -webkit-transform: scale(0.0);
  }

  40% {
    transform: scale(0.5);
    -webkit-transform: scale(0.5);
  }
}

// 新增样式
.device-select-card {
  background-color: #ffffff;
  border-radius: 50rpx;
  padding: 30rpx;
  margin-top: 15rpx;
}

.search-bar {
  display: flex;
  flex-direction: column;
  margin-bottom: 20rpx;

}

.search-label {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 15rpx;
  padding: 0 80rpx 0 10rpx;
}

.search-input-container {
  position: relative;
  width: 100%;
}

.search-input {
  width: 80%;
  height: 80rpx;
  border-radius: 40rpx;
  background-color: #f5f5f5;
  padding: 0 80rpx 0 42rpx;
  font-size: 28rpx;
}

.uni-input-placeholder {
  position: absolute;
  top: auto !important;
  left: 5px;
  color: grey;
  overflow: hidden;
  text-overflow: clip;
  white-space: pre;
  word-break: keep-all;
  line-height: inherit;
}

/* 添加到你的全局样式表或组件样式中 */
.uni-placeholder {
  position: fixed;  /* 固定定位，不随页面滚动 */
  top: 0;           /* 固定在顶部 */
  left: 0;          /* 左对齐 */
  right: 0;         /* 右对齐，确保宽度填满 */
  z-index: 999;     /* 较高的z-index确保不被其他元素覆盖 */
  background-color: #fff; /* 背景色，防止透明时显示下方内容 */
  /* 可选：添加阴影效果增强视觉层次 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 为了防止固定定位导致内容被遮挡，给页面内容添加上边距 */
.page-content {
  padding-top: 50px; /* 根据你的uni-placeholder高度调整 */
}

.search-icon {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 40rpx;
  height: 40rpx;
}

.category-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
  margin-bottom: 20rpx;
}

.category-tab {
  padding: 20rpx 0;
  margin-right: 40rpx;
  position: relative;
  font-size: 28rpx;
  color: #666;
}

.category-tab.active {
  color: #0080ff;
  font-weight: 500;
}

.category-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 4rpx;
  background-color: #0080ff;
}

.device-grid {
  height: 400rpx;
}

.device-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 10rpx 0;
}

.device-item {
  width: 48%;         /* 由23%改为48%，使一行显示2个卡片 */
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;   /* 添加白色背景 */
  border-radius: 20rpx;        /* 添加圆角 */
  padding: 20rpx;              /* 添加内边距 */
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);  /* 添加阴影效果 */
}

.device-image {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 15rpx;
  align-self: flex-start;      /* 图片左对齐 */
}

.device-name {
  font-size: 28rpx;            /* 增大字体 */
  color: #333;
  font-weight: 500;            /* 加粗 */
  text-align: left;            /* 文本左对齐 */
  margin-bottom: 10rpx;
}

.device-brand {                /* 新增样式 */
  font-size: 22rpx;
  color: #888;
  text-align: left;
}
</style>